#!/usr/bin/env python3
"""
煤炉监控系统 - FastAPI应用入口

实时监控煤炉上新商品推送服务
"""

from contextlib import asynccontextmanager
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from app.config import settings
from app.database import engine, Base
from app.api.v1 import auth, users, monitors, products, websocket


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时创建数据库表
    Base.metadata.create_all(bind=engine)
    print("[启动] 煤炉监控系统启动完成")
    yield
    # 关闭时清理资源
    print("[关闭] 煤炉监控系统关闭")


# 创建FastAPI应用
app = FastAPI(
    title="煤炉监控系统",
    description="实时监控煤炉上新商品推送服务",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc",
    lifespan=lifespan
)

# CORS中间件配置
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境应该限制具体域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册API路由
app.include_router(auth.router, prefix="/api/v1/auth", tags=["🔐 认证"])
app.include_router(users.router, prefix="/api/v1/users", tags=["👤 用户"])
app.include_router(monitors.router, prefix="/api/v1/monitors", tags=["📊 监控"])
app.include_router(products.router, prefix="/api/v1/products", tags=["🛍️ 商品"])
app.include_router(websocket.router, prefix="/ws", tags=["🔌 WebSocket"])


@app.get("/", tags=["🏠 首页"])
async def root():
    """系统首页"""
    return {
        "message": "🔥 煤炉监控系统API",
        "version": "1.0.0",
        "status": "running",
        "docs": "/docs"
    }


@app.get("/health", tags=["🏥 健康检查"])
async def health_check():
    """健康检查接口"""
    return {
        "status": "healthy",
        "database": "connected",
        "redis": "connected",
        "celery": "running"
    }


if __name__ == "__main__":
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=settings.DEBUG,
        log_level=settings.LOG_LEVEL.lower()
    )
